using System;
using System.ComponentModel;
using System.Reflection;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Util;
using Java.Lang;
using Java.Util;
using NetworkCommsDotNet;
using Exception = System.Exception;
using String = System.String;

namespace jivemessenger
{
    [Service]
  //  [IntentFilter(new String[] { "com.jivemessenger.JiveService" })]
    public class JiveService : Service
    {
        private JiveServiceBinder _binder;
        public NetworkConnection Connection;
        public event EventHandler<NewChatMessageEventArgs> NewMessageEvent;
        public event EventHandler<JiveServiceConnectEventArgs> OnDisconnectEvent;
        private Thread reconnectThread;
        private bool isConnectingManually;
        private bool ignoreDisconnectEvent;

        //  private bool isReconnecting;
        public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
        {
            Log.Debug(StaticSettings.JiveTag, "JiveService started");


            return StartCommandResult.NotSticky;
        }

        public override bool OnUnbind(Intent intent)
        {
            try
            {
             //   NetworkComms.Shutdown();
            }
            catch (Exception err)
            {

            }
            return base.OnUnbind(intent);
        }

        public override IBinder OnBind(Intent intent)
        {
            this._binder = new JiveServiceBinder(this);
            Connection = new NetworkConnection();
            Connection.OnReceivedMessage += OnReceivedMessage;
            Connection.OnDisconnectEventHandler += OnNetworkDisconnect;
            return this._binder;
        }
        public override void OnDestroy()
        {
            Connection.OnReceivedMessage -= OnReceivedMessage;
            Connection.OnDisconnectEventHandler -= OnNetworkDisconnect;
            base.OnDestroy();
        }
        public void ManualConnect()
        {
            //NetworkComms.Shutdown();
            isConnectingManually = true;
            
            if (Connect(true, true))
                isConnectingManually = false;
            //else
            //{
            //    if (OnDisconnectEvent != null)
            //        OnDisconnectEvent(this, new JiveServiceConnectEventArgs(true, true));
            //}
        }

        public void RunBeforeUnbind()
        {
          //  if (Connection == null)
           //     return;
          //  if (Connection.OnDisconnectEventHandler == null)
             //   return;
            //Connection.OnDisconnectEventHandler -= OnNetworkDisconnect;
            ignoreDisconnectEvent = true;
        }

        private bool Connect(bool createDisconnectHandler, bool createReceiveMessageHandler)
        {
            try
            {
                NetworkComms.Shutdown();
                //Connection = null;
                //GC.Collect();
               // Connection = new NetworkConnection();
                //if (createReceiveMessageHandler)
                //    Connection.OnReceivedMessage += OnReceivedMessage;
                //if (createDisconnectHandler)
                //    Connection.OnDisconnectEventHandler += OnNetworkDisconnect;
                // throw new Exception();

                if (!Connection.Connect())
                {

                    return false;
                }
            }
            catch (Exception err)
            {
                Log.Error(StaticSettings.JiveTag, "Error in network connect: " + err);
                return false;
            }
            return true;
        }

        private void OnNetworkDisconnect(object sender, NetworkConnection.OnDisconnectEventArgs e)
        {
            try
            {
                Client.IsLoggedIn = false;
                if (ignoreDisconnectEvent)
                    return;
                //ConnectUpdateUI(false);

                //Connection.OnReceivedMessage -= OnReceivedMessage;
                //Connection.OnDisconnectEventHandler -= OnNetworkDisconnect;

                if (StaticSettings.AutoReconnect && !isConnectingManually)
                {
                    if (reconnectThread == null || !reconnectThread.IsAlive)
                    {
                        if (OnDisconnectEvent != null)
                            OnDisconnectEvent(this, new JiveServiceConnectEventArgs(true, false));
                        reconnectThread = null;
                        reconnectThread = new Thread(() =>
                            {
                                //isReconnecting = true;
                                int tries = 0;
                                while (true)
                                {
                                    try
                                    {
                                        //if (tries > 100)
                                        //{
                                        //    //     isReconnecting = false;


                                        //    //if (OnDisconnectEvent != null)
                                        //    //    OnDisconnectEvent(this, new JiveServiceConnectEventArgs(true, true));
                                        //    return;
                                        //}
                                        //try
                                        //{
                                        //    NetworkComms.Shutdown();
                                        //}
                                        //catch (Exception err)
                                        //{
                                        //    Log.Error("JiveMessenger", "Error shutting down networkcomms: " + err);
                                        //}
                                        bool success = Connect(false, false);
                                        if (success || tries>100)
                                        {

                                            break;
                                            //    isReconnecting=false;
                                            //break;
                                        }
                                        //NetworkComms.RemoveGlobalIncomingPacketHandler("ChatMessage");
                                        int time = tries < 5 ? 5000 : 30000;
                                        Thread.Sleep(time);
                                    }
                                    catch (Exception err)
                                    {
                                        Log.Error("jiveMessenger", "error in reconnect thread: " + err);
                                    }
                                    tries++;
                                }

                            });

                        reconnectThread.Start();
                    }
                }
                else
                {
                    //NetworkComms.RemoveGlobalIncomingPacketHandler("ChatMessage");
                    if (OnDisconnectEvent != null)
                        OnDisconnectEvent(this, new JiveServiceConnectEventArgs(true, true));
                }
            }
            catch (Exception err)
            {
                Log.Error("jiveMessenger", "error in reconnect thread: " + err);
            }
            //   StopSelf();
        }
        private void OnReceivedMessage(object sender, NetworkConnection.OnReceivedMessageEventArgs e)
        {
            if (NewMessageEvent != null)
                NewMessageEvent(this, new NewChatMessageEventArgs(e.Msg));
        }


    }
}